package myJs.cps

import myJs.Implicits._
import myJs.myPkg.DatetimePickerOptions
import myJs.myPkg.jquery.$
import myJs.tool.Tool
import org.scalajs.dom.{Event, html}
import org.scalajs.dom.html.{Div, Input}
import slinky.core.{FunctionalComponent, SyntheticEvent, TagElement}
import slinky.core.annotations.react
import slinky.core.facade.Hooks.useEffect
import slinky.core.facade.React
import slinky.web.html._

/**
 * Created by yz on 21/1/2022
 */
@react object PureDateTimePickerCp {

  case class Props(placeHolder: String = "", name: String = "", onChangeF: String => Unit, value: String,
                   pattern: String = "yyyy-mm-dd hh:ii:ss"
                  )

  val component = FunctionalComponent[Props] { props =>

    val divRef = React.createRef[Div]

    object FTool {

      def valueChange = (e: SyntheticEvent[TagElement#RefType, Event]) => {
        val v = e.target.asInstanceOf[html.Input].value
        props.onChangeF(v)
      }


    }

    useEffect(() => {
      val options = DatetimePickerOptions(format = props.pattern, autoclose = true, language = "zh-CN", minuteStep = 1)
      $(divRef.current).datetimepicker(options)
    }, List()
    )

    useEffect(() => {
      $(divRef.current).offThenOn("changeDate", (e: Event) => {
        val myV = $(divRef.current).find(":input").myVal
        props.onChangeF(myV)
      })
      () => {
        $(divRef.current).off("changeDate")
      }
    }
    )

    useEffect(() => {
      $(divRef.current).datetimepicker("update", props.value)
    }, List(props.value)
    )

    div(className := "input-group date datePicker", ref := divRef,
      input(`type` := "text", className := "filterInput form-control startTime",
        name := props.name, width := "100%", placeholder := props.placeHolder,
        value := props.value),
      span(className := "input-group-addon",
        span(className := "glyphicon glyphicon-time")
      )
    )


  }

}
